Lesson 2 - Trace tables

Computers run code in a logical manner. Each statement is run serially unless a loop, function or selection is encountered. It is perfectly possible to read and run code on paper. This is known as a trace through the code. In order to make the process easier a table is created which will show the current contents of variables. This is called a trace table.


x = 1
temp = "*"
while x < = 5
	print temp
	temp = temp + "*"
	x = x + 1

Step 1 - Create a blank table

x
temp
output
     
     

You look through the code looking for any variables which are used. Each variable will be a column in the table. There are only two variables in the above code which is why there are only two columns. The final column is for output.

Step 2 - Run the code!

Each time a variable changes you write down the new result in the table. Running the first two lines would result in -

x
temp
output
1 *  
     

Step 3 - Dealing with loops

Loops will only run their code if the condition has been met. The condition x < = 5 will be replaced with 1 <= 5. To work this out you simply look at the current value of x. If the condition is met then you continue with code within the loop. Running the first loop will result in the following additions to the trace table.

x
temp
output
1 * *
2 **  

Once a loop is done it will always loop back to the start of the loop and re-test the condition. The trace table below shows the final result of the trace (The code is included to save scrolling!)


x = 1
temp = "*"
while x < = 5
	print temp
	temp = temp + "*"
	x = x + 1

 

x
temp
output
1 * *
2 ** **
3 *** ***
4 **** ****
5 ***** *****
6 ******  

Step 4 - Dealing with functions

Dealing with functions is a little different as you need to keep track of where to jump back to. To help we will add two extra columns, function name and return value. Below is an example trace table and code sample.


def foo(x):
	y = bar(x * 2)
	print y
	return y

def bar(z):
	print z
	return z - 1

print foo(5)
print bar(foo(2))

x
y z function name return
output
5     foo    
    10 bar 9 10
  9     9 9
          9
2     foo    
    4 bar 3 4
  3     3 3
    3 bar 2 3
          2

There are a lot of spaces in the table above. The reason for this is that each new function call is given a new row. This is help keep track of what functions have been called.

Tips